<template>
	<!-- 登录容器 -->
	<view class="login-container">
		<view class="logo-container">
			<image src="/static/logo2.png" mode=""></image>
		</view>
		<!-- 登录卡片 -->
		<view class="login-card">
			<!-- 顶部标签 -->
			<view class="tabs">
				<!-- 患者标签 -->
				<view class="tab" :class="{ active: userType === 0 }" @click="userType = 0">患者</view>
				<!-- 医生标签 -->
				<view class="tab" :class="{ active: userType === 1 }" @click="userType = 1">医生</view>
			</view>

			<!-- 手机号输入区域（两种登录方式通用） -->
			<view class="form-item phone-input">
				<!-- 国家代码 -->
				<view class="country-code">
					<text>+86</text>
				</view>
				<!-- 手机号输入框 -->
				<input v-model="form.phone" placeholder="请输入手机号" type="number" maxlength="11" />
			</view>

			<!-- 验证码登录/注册 -->
			<view v-if="currentView === 'code'">
				<!-- 验证码区域 -->
				<view class="form-item verify-code">
					<!-- 验证码输入框 -->
					<input v-model="form.verifyCode" placeholder="请输入短信验证码" type="number" maxlength="6" />
					<!-- 获取验证码按钮 -->
					<button class="verify-btn" @click="getVerifyCode" :disabled="countdown > 0">
						{{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
					</button>
				</view>
			</view>

			<!-- 密码登录 -->
			<view v-if="currentView === 'password'">
				<!-- 密码输入区域 -->
				<view class="form-item password-input">
					<!-- 密码图标 -->
					<text class="password-icon">🔒</text>
					<!-- 密码输入框 -->
					<input v-model="form.password" placeholder="请输入密码" type="password" />
				</view>
			</view>

			<!-- 登录/注册按钮 -->
			<button type="submit" @click="handleLogin" class="login-btn">
				{{ currentView === 'code' ? '快捷登录' : '登录' }}
			</button>

			<!-- 底部选项 -->
			<view class="bottom-options">


				<!-- 同意隐私政策 -->
				<!-- <view class="checkbox-row">
					<label class="checkbox-item">
						<!-- 勾选框 -->
				<!-- <checkbox value="agree" color="#ff5a5f" :checked="form.agreePolicy" @change="checkboxChange" />
						<text>我已详细阅读并同意 <text class="link-text">《隐私政策》</text></text>
					</label> -->
				<!-- 切换登录方式 -->
				<!-- 切换密码登录和验证码登录 -->
				<!-- <text class="toggle-login" @click="toggleLoginView">
						{{ currentView === 'password' ? '短信快捷登录' : '密码登录' }}
					</text>
				</view> -->

				<view class="checkbox-row">
					<label class="checkbox-item" @click="toggleAgreePolicy">
						<!-- 自定义UI来显示选中状态 -->
						<view class="custom-checkbox" :class="{'checked': form.agreePolicy}">
							<!-- 可以放一个勾选图标或者用样式显示选中状态 -->
						</view>
						<text>我已详细阅读并同意 <text class="link-text" @click="goPrivacy">《隐私政策》</text></text>
					</label>
					<text class="toggle-login" @click="toggleLoginView">
						{{ currentView === 'password' ? '短信快捷登录' : '密码登录' }}
					</text>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				globaApi: '',
				// 用户类型，0 表示患者，1 表示医生
				userType: 0,
				// 当前登录视图，'code' 表示验证码登录/注册，'password' 表示密码登录
				currentView: 'code',
				checkbox: '',
				// 表单数据
				form: {
					phone: '',
					verifyCode: '',
					password: '',
					agreePolicy: false
				},
				// 倒计时定时器
				timer: null,
				// 倒计时秒数
				countdown: 0
			};
		},
		onLoad() {
			this.globaApi = getApp().globalData.baseUrl
			console.log(this.globaApi)
		},
		methods: {
			// 处理勾选同意隐私政策的变化
			// checkboxChange(e) {
			// 	// 确保我们获取正确的值
			// 	if (e.detail && e.detail.value) {
			// 		this.form.agreePolicy = e.detail.value.indexOf('agree') !== -1;
			// 	} else {
			// 		this.form.agreePolicy = false;
			// 	}
			// 	console.log('协议同意状态:', this.form.agreePolicy);
			// },
			toggleAgreePolicy() {
				this.form.agreePolicy = !this.form.agreePolicy;
				console.log('协议同意状态:', this.form.agreePolicy);
			},
			// 切换登录视图
			toggleLoginView() {
				this.currentView = this.currentView === 'code' ? 'password' : 'code';
			},
			// 验证手机号
			validatePhone() {
				if (!this.form.phone || this.form.phone.length !== 11) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return false;
				}
				return true;
			},
			// 获取验证码
			getVerifyCode() {
				if (!this.validatePhone()) return;
				if (this.countdown > 0) return;

				// 显示加载提示
				uni.showLoading({
					title: '发送中...'
				});
				console.log(this.form.phone)
				// 调用 API 发送验证码
				// 该 API 应检查手机号是否存在并进行相应处理
				uni.request({
					url: `${this.globaApi}/auth/send-code`,
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						phone: this.form.phone,
						// userType: this.userType
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.code === 0) {
							uni.showToast({
								title: '验证码已发送',
								icon: 'success'
							});

							// 开始倒计时
							this.countdown = 60;
							this.timer = setInterval(() => {
								this.countdown--;
								if (this.countdown <= 0) {
									clearInterval(this.timer);
								}
							}, 1000);
						} else {
							uni.showToast({
								title: res.data.message || '发送失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					}
				});
			},
			// 处理登录
			async handleLogin() {
				if (!this.validatePhone()) return;

				if (this.currentView === 'code' && !this.form.verifyCode) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return;
				}

				if (this.currentView === 'password' && !this.form.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return;
				}

				if (!this.form.agreePolicy) {
					uni.showToast({
						title: '请阅读并同意隐私政策',
						icon: 'none'
					});
					return;
				}

				try {
					// 显示加载提示
					uni.showLoading({
						title: '登录中...'
					});

					// 准备请求数据
					const requestData = {
						phone: this.form.phone,
						identity: this.userType
					};

					// 根据登录方式添加验证码或密码
					if (this.currentView === 'code') {
						requestData.code = this.form.verifyCode;
						// 使用基于验证码的端点，处理登录和注册
						var endpoint = `${this.globaApi}/auth/codeLogin`;
					} else {
						requestData.password = this.form.password;
						// 密码登录需要已有账户
						var endpoint = `${this.globaApi}/auth/login`;
					}

					// 发送登录/注册请求
					uni.request({
						url: endpoint,
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						data: requestData,
						success: (res) => {
							uni.hideLoading();
							if (this.userType === 0) {
								var endpoint = `${this.globaApi}/userInfo/getUserInfoByUserId`;
								uni.setStorageSync('userType', 0);
							} else {
								var endpoint = `${this.globaApi}/doctor/getDoctorById`;
								uni.setStorageSync('userType', 1);
							}

							if (res.data.code === 200) {
								uni.setStorageSync('token', res.data.data.token);
								console.log(res.data.data.token)
								const userId = res.data.data.userId
								uni.setStorageSync('userId', res.data.data
									.id);
								uni.showToast({
									title: '登录成功',
									icon: 'success'
								});

								uni.request({
									url: endpoint,
									method: 'POST',
									header: {
										'Content-Type': 'application/x-www-form-urlencoded'
									},
									data: {
										userId: userId
									},
									success: (res) => {

										if (res.data.code === 200) {
											console.log(res)
											// 将用户信息存储在本地存储中
											uni.setStorageSync('username', res.data.data
												.name);
											uni.setStorageSync('avatar', res.data.data.avatar);
											uni.setStorageSync('sex', res.data.data.sex);
											uni.setStorageSync('birthday', res.data.data
												.birthday);
											uni.setStorageSync('introduction', res.data
												.data.introduction);
											uni.setStorageSync('telephone', res.data
												.data.phone);
										}
									},
									fail: () => {
										uni.hideLoading();
										uni.showToast({
											title: '查询信息错误，请稍后重试',
											icon: 'none'
										});
									}

								})

								// 导航到主页
								setTimeout(() => {
									uni.switchTab({
										url: '/pages/index/index'
									});
								}, 1500);
							} else {
								uni.showToast({
									title: res.data.message || '登录失败',
									icon: 'none'
								});
							}
						},
						fail: () => {
							uni.hideLoading();
							uni.showToast({
								title: '网络错误，请稍后重试',
								icon: 'none'
							});
						}
					});
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: error.message || '登录失败，请检查网络',
						icon: 'none'
					});
				}
			},
			goPrivacy() {
				uni.navigateTo({
					url: '/pages/login/privacy'
				})
			}
		},
		// 页面卸载时清除定时器
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer);
			}
		}
	};
</script>

<style scoped>
	/* 登录容器样式 */
	.login-container {
		background-color: #f5f5f5;
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.logo-container image {
		border-radius: 20rpx;
		width: 320rpx;
		height: 320rpx;
		margin-bottom: 20rpx;
	}

	/* 登录卡片样式 */
	.login-card {
		background: white;
		width: 90%;
		padding: 10px 0 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
		border-radius: 20rpx;
	}

	/* 标签容器样式 */
	.tabs {
		display: flex;
		border-bottom: 1px solid #eee;
	}

	/* 标签样式 */
	.tab {
		flex: 1;
		text-align: center;
		padding: 15px 0;
		font-size: 16px;
		color: #999;
		position: relative;
	}

	/* 激活标签样式 */
	.tab.active {
		color: #333;
		font-weight: bold;
	}

	/* 激活标签下划线样式 */
	.tab.active::after {
		content: '';
		position: absolute;
		bottom: -1px;
		left: 20%;
		width: 60%;
		height: 2px;
		background-color: #ff5a5f;
	}

	/* 表单项样式 */
	.form-item {
		margin: 20px 15px;
		border: 1px solid #eee;
		border-radius: 5px;
		height: 45px;
		display: flex;
		align-items: center;
	}

	/* 手机号输入和密码输入样式 */
	.phone-input,
	.password-input {
		padding-left: 10px;
	}

	/* 国家代码样式 */
	.country-code {
		color: #999;
		margin-right: 10px;
		font-size: 14px;
		display: flex;
		align-items: center;
	}

	/* 密码图标样式 */
	.password-icon {
		color: #999;
		margin-right: 10px;
		font-size: 18px;
	}

	/* 输入框样式 */
	input {
		flex: 1;
		height: 100%;
		border: none;
		font-size: 14px;
		padding: 0 10px;
	}

	/* 获取验证码按钮样式 */
	.verify-btn {
		background-color: #4990e2;
		color: white;
		border: none;
		border-radius: 5px;
		height: 35px;
		line-height: 35px;
		padding: 0 15px;
		margin-right: 5px;
		font-size: 14px;
	}

	/* 禁用状态下的获取验证码按钮样式 */
	.verify-btn[disabled] {
		background-color: #9cc3f0;
	}

	/* 登录按钮样式 */
	.login-btn {
		width: 90%;
		margin: 20px auto;
		background-color: #ff5a5f;
		color: white;
		border: none;
		border-radius: 5px;
		height: 45px;
		line-height: 45px;
		font-size: 16px;
	}

	/* 底部选项样式 */
	.bottom-options {
		margin: 0 15px;
	}

	/* 复选框行样式 */
	.checkbox-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10px;
		font-size: 12px;
		color: #999;
	}

	/* 复选框项样式 */
	.checkbox-item {
		display: flex;
		align-items: center;
	}

	.custom-checkbox {
		width: 18px;
		height: 18px;
		border: 1px solid #ddd;
		border-radius: 3px;
		margin-right: 5px;
		position: relative;
	}

	.custom-checkbox.checked {
		background-color: #ff5a5f;
		border-color: #ff5a5f;
	}

	.custom-checkbox.checked:after {
		content: '✓';
		color: white;
		position: absolute;
		font-size: 12px;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	/* 链接文本样式 */
	.link-text {
		color: #4990e2;
	}

	/* 切换登录方式文本样式 */
	.toggle-login {
		color: #999;
		font-size: 12px;
	}
</style>